'use strict';

const path = require('path')
const Package = require('@fs-cli-dev/package')
const log = require('@fs-cli-dev/log')
const { exec: sqawn } = require('@fs-cli-dev/utils')

const SETTINGS = {
    'init': '@fs-cli-dev/log'
}
const CACHE_DIR = 'dependencies'
let pkg

async function exec() {
    let storeDir
    let targetPath = process.env.CLI_TARGET_PATH
    const homePath = process.env.CLI_HOME_PATH

    log.verbose('targetPath:', targetPath)
    log.verbose('homePath:', homePath)

    const program = arguments[arguments.length - 1]

    const cmdName = program.name()
    const packageName = SETTINGS[cmdName]
    const packageVersion = 'latest'

    if (!targetPath) {
        // 生成缓存路径
        targetPath = path.resolve(homePath, CACHE_DIR)
        storeDir = path.resolve(targetPath, 'node_modules')

        log.verbose('targetPath:', targetPath)
        log.verbose('storeDir:', storeDir)

        pkg = new Package({
            targetPath: targetPath,
            storeDir: storeDir,
            packageName: packageName,
            packageVersion: packageVersion
        })

        if (await pkg.exists()) {
            console.log('update');
            // 存在更新
            pkg.update()

        } else {
            console.log('install');
            // 不存在安装
            await pkg.install()
        }

    } else {
        pkg = new Package({
            targetPath: targetPath,
            packageName: packageName,
            packageVersion: packageVersion
        })
        console.log(await pkg.exists());
        const rootFile = await pkg.getRootFilePath()
        console.log(rootFile);
        if (rootFile) {
            try {
                // 在当前进程中调用
                // require(rootFile).call(null, Array.from(arguments))
                // 在node子进程中调用 cp.fork
                // node -e 表示执行后面代码
                // node - e console.log('111')
                // const code = "console.log('111')"
                const args = Array.from(arguments)
                const cmd = args[args.length - 1]
                const obj = Object.create(null)
                Object.keys(cmd).forEach(key => {
                    if (cmd.hasOwnProperty(key) && !key.startsWith('_') && key !== 'parent') {
                        obj[key] = cmd[key]
                    } else {
                        if (key === '_optionValues') {
                            obj['_optionValues'] = cmd['_optionValues']
                        }
                    }
                })

                args[args.length - 1] = obj

                const code = `require('${rootFile}').call(null, ${JSON.stringify(args)})`

                // window cp.spawn('cmd', ['/c', 'node', '-e', code],
                // mac
                // const child = cp.spawn('node', ['-e', code], {
                //     cwd: process.cwd(),
                //     // 不需要监听，直接在父进程中输出
                //     stdio: 'inherit'
                // })
                const child = sqawn('node', ['-e', code], {
                    cwd: process.cwd(),
                    // 不需要监听，直接在父进程中输出
                    stdio: 'inherit'
                })
                child.on('error', err => {
                    log.error(e.message)
                    process.exit(1)
                })
                child.on('exit', e => {
                    log.verbose('命令执行成功: ' + e)
                    process.exit(e)
                })

            } catch (error) {
                log.error(error.message)
            }
        }


    }





}




module.exports = exec;